// pages/UserCenter/OrderList.js
var util = require('../../utils/util.js')
var app = getApp();
var url = util.baseUrl
var statusDic = {
  '01': "已取消",
  '02': "已退款",
  '05': "已删除",
  '11': "待付款",
  '21': "待生产",
  '25': "生产中",
  '31': "待收货",
  '51': "已成交",
  '61': "已评价"
}

var buttonDic = {
  "01": [{
    "title": "删除订单",
    "action": "presentDeleteButtonAction"
  }],
  "02": [{
    "title": "删除订单",
    "action": "presentDeleteButtonAction"
  }],
  "11": [{
      "title": "取消订单",
      "action": "presentCancelButtonAction"
    },
    {
      "title": "付  款",
      "action": "presentPaymentButtonAction"
    }
  ],
  "31": [{
    "title": "查看物流",
    "action": "presentLookWuliuButtonAction"
  }],
  "51": [{
      "title": "查看物流",
      "action": "presentLookWuliuButtonAction"
    },
    {
      "title": "删除订单",
      "action": "presentDeleteButtonAction"
    },
    {
      "title": "评 价",
      "action": "presentEvaluateButtonAction"
    }
  ],
  "61": [{
      "title": "查看物流",
      "action": "presentLookWuliuButtonAction"
    },
    {
      "title": "删除订单",
      "action": "presentDeleteButtonAction"
    }
  ]
}
Page({
      data: {
        titleList: [{
          title: '线上订单',
          id: '0'
        }, {
          title: '待付款',
          id: '11'
        }, {
          title: '待收货',
          id: '31'
        }, {
          title: '待评论',
          id: '51'
        }], //顶部按钮
        isTotal: true, //是否显示下拉菜单
        orderStatusList: [{
          title: 'APP订单',
          id: '0'
        }, {
          title: '线下订单',
          id: '9'
        }],
        isUnderLine: true, //是否隐藏线下订单
        underList: [], //线下订单列表
        underItemPic: '',
        status: '',
        dataList: [],
        windowwidth: app.globalData.deviceInfo.windowWidth,
        windowheight: app.globalData.deviceInfo.windowHeight,
        havaDefaultAddress: false,
        item: {},
        addressData: {},
        phoneNumber: '',
        address: '',
        clientName: '',
        productInfo: {},
        postage: 0,
        time: '',
        price: 0
      },
      onLoad: function(options) {
        // 页面初始化 options为页面跳转所带来的参数
        this.setData({
          status: options.status
        })
        this.page = 0
        this.loadData(options.status, this.page)
        var _this = this
        let mohuanUser = app.globalData.mohuanUser
        let memberId = mohuanUser.memberId
        this.memberId = memberId
        //获取地址
        util.request(`/c2mwebservice/api/v1/members/${memberId}/addresses`, function(res) {
          let datas = res.returnData.currentList
          if (datas) {
            let data = datas.filter(function(obj) {
              if (obj.isDefault) {
                return true;
              }
            })[0];
            if (!data) {
              data = res.returnData.currentList[0]
            }
            _this.setData({
              phoneNumber: data.phoneNo,
              address: `${data.city}${data.suburb}${data.detail}`,
              clientName: data.receiver,
              addressData: data,
              havaDefaultAddress: true,
            })
          } else {
            _this.setData({
              havaDefaultAddress: false,
              addressData: {},
            })
          }


        }, function(res) {
          wx.showToast({
            title: res.data.returnMsg,
            duration: 2000
          })
        })
        wx.getStorage({
          key: 'productInfo',
          success: function(res) {
            let product = {}
            if (res.data.suit) {
              product.goodsName = res.data.suit.suitNameCn
              product.materialName = res.data.goods[0].customization.material.materialName
              product.size = `上衣：${res.data.goods[0].size.size} 裤子：${res.data.goods[1].size.size}`
              product.count = res.data.suit.suitCount
              product.price = res.data.suit.suitPrice
              product.goodsImg = params.productImage
            } else {
              product.goodsName = res.data.goods[0].goodsName
              if (res.data.goods[0].customization.material) {
                product.materialName = res.data.goods[0].customization.material.materialName
              } else {
                product.materialName = '默认面料'
              }
              product.size = `尺码:${res.data.goods[0].size.size}`
              product.count = res.data.goods[0].count
              product.price = res.data.goods[0].price
              product.goodsImg = params.productImage
            }
            _this.setData({
              item: product,
              productInfo: res.data,
            })

            // 套装
            if (res.data.suit) {
              params.totalPrice = res.data.suit.suitPrice
            } else {
              params.totalPrice = res.data.goods[0].price
            }
            _this.totalPrice = params.totalPrice

            let timeParams = {}
            for (let index = 0; index < res.data.goods.length; index++) {
              timeParams[res.data.goods[index].customization.categoryName] = res.data.goods[index].count
            }

            _this._loadFreight(function(res) {
              let freight = 0
              if (res.length > 0) {
                for (let i = 0; i < res.length; i++) {
                  if (res[i].amountRange > _this.totalPrice) {
                    freight = res[i].postage
                    break;
                  }
                }
              }
              let p = parseFloat(_this.totalPrice) * parseFloat(product.count) + parseFloat(freight)
              _this.setData({
                postage: freight,
                price: p
              })
            }, function(res) {

            })

            _this._loadPredictTime(timeParams, function(res) {
              _this.setData({
                time: res
              })
            }, function(res) {

            })
          },
          fail: function(res) {},
          complete: function() {
            wx.removeStorage({
              key: 'productInfo',
            })
          }
        })
      },
      onReady: function() {
        // 页面渲染完成
      },
      onShow: function() {
        // 页面显示
        let _this = this
        if (!this.data.havaDefaultAddress || this.hasChangeAddress) {
          wx.getStorage({
            key: 'Address',
            success: function(data) {
              let phoneNumber = data.data.phoneNo
              let clientName = data.data.receiver
              let address = `${data.data.city}${data.data.suburb}${data.data.detail}`
              _this.setData({
                phoneNumber: phoneNumber,
                address: address,
                clientName: clientName,
                addressData: data.data,
                havaDefaultAddress: true
              })
              _this.hasChangeAddress = false
            },
            fail: function() {},
            complete: function() {
              wx.removeStorage({
                key: 'Address'
              })
            }
          })
        }
      },
      onHide: function() {
        // 页面隐藏
      },
      onUnload: function() {
        // 页面关闭
      },
      //获取商品尺寸
      getSizeFromGoods: function(goods) {
        let goodsSize = goods.size;
        let sizeType = goodsSize.sizeType;
        if (sizeType == 0 || sizeType == 2 || sizeType == 4) {
          return sizeType == 0 ? '量体订单' : (sizeType == 2 ? '量体数据' : '均码');
        }
        let sizeStr = goodsSize.size + '号';
        if (goodsSize.bodyShape.length) sizeStr += goodsSize.bodyShape;
        let sizeString;
        let tempStr = '';
        for (let extend of goodsSize.goodsSizeExtended) {
          if (extend.value != 0) {
            if (tempStr.length) {
              tempStr = ',' + tempStr + extend.id + extend.value;
            } else {
              tempStr = tempStr + extend.id + extend.value;
            }
          }
        }
        if (tempStr.length) {
          sizeString = sizeStr + tempStr;
          return sizeString;
        }
        if (sizeStr == '(null)号') {
          sizeStr = '使用预约量体数据';
        }
        return sizeStr;
      },
      //滚动
      lower: function(e) {
        this.page += 1
        this.loadData(this.data.status, this.page)
      },
      //滚动
      upper: function(e) {
        this.page = 0
        this.loadData(this.data.status, this.page)
      },
      //调接口返回所需订单列表
      loadData(status, page) {
        var that = this;
        that.structureData("", "")
        wx.showToast({
          title: 'loading..',
          icon: 'loading',
          uration: 20000
        })
        util.postRequest(`/c2mwebservice/api/v2/trade/${getApp().globalData.mohuanUser.memberId}/myOrderList/` + status, {
          "page": page,
          "row": 100
        }, function(res) {
          wx.hideToast()
          let returnData = res.returnData
          that.structureData(returnData, status)
        }, function(res) {
          wx.hideToast()
          console.log(res)
        })
      },
      //获取商品详细
      structureData(returnData, status) {
        let dataList = this.page == 0 ? [] : this.data.dataList;
        for (let obj of returnData) {
          let order = {};


          order.goodsList = [];

          for (let littleOrder of obj.orderList) {
            let item = {};
            let fGoods = littleOrder.goods[0];
            if (fGoods.goodsType == '2') {
              continue
            }
            let isSuit = littleOrder.goods.length > 1;
            item.goodsName = isSuit ? littleOrder.suit.suitNameCn : fGoods.goodsName;
            if (fGoods.customization.material) {
              item.materialName = fGoods.customization.material.materialName;
              item.materialCode = fGoods.customization.material.materialCode ? fGoods.customization.material.materialCode : ""
            } else {
              item.materialName = "默认面料";
              item.materialCode = "";
            }
            item.size = isSuit ? `西服尺寸：${this.getSizeFromGoods(fGoods)}\n西裤尺寸：${this.getSizeFromGoods(littleOrder.goods[1])}` : `尺寸：${this.getSizeFromGoods(fGoods)}`;
            item.price = util.moneyPaddingZero(isSuit ? littleOrder.suit.suitPrice : fGoods.price, 2);
            item.count = fGoods.count;
            item.goodsImg = isSuit ? littleOrder.suit.suitPicUrl : fGoods.preview[0];
            if (!item.goodsImg || item.goodsImg.length == 0) item.goodsImg = '/images/default.png';

            //评价所需
            item.tradeOrderId = littleOrder.salesId
            if (fGoods.goodsType == 3 || fGoods.goodsType == 4) {
              item.goodsIdOrDesignCode = fGoods.goodsId //美物是存商品ID，造物时存定制款式工艺
              item.isCustom = "0" //美物还是造物
            } else {
              item.goodsIdOrDesignCode = fGoods.customization.design //美物是存商品ID，造物时存定制款式工艺
              item.isCustom = "1" //
            }
            if (isSuit) {
              item.suiteId = littleOrder.suit.suitId
              delete item.goodsIdOrDesignCode //套装就不需要这个了
            }
            // 

            order.goodsList.push(item);
          }
          if (order.goodsList.length == 0) {
            continue
          }
          order.brandName = obj.brandName;
          order.orderStatus = statusDic[obj.orderStatus];
          order.buttonArr = buttonDic[obj.orderStatus];
          order.goodsCount = obj.goodsSum;
          order.totalPrice = util.moneyPaddingZero(parseFloat(obj.totalPrice) + parseFloat(obj.payment.balance), 2);
          order.postage = util.moneyPaddingZero(obj.postage, 2);
          order.discount = util.moneyPaddingZero(parseFloat(obj.goodsTotalPrice) - parseFloat(obj.totalPrice) - parseFloat(obj.payment.balance), 2);
          order.orderId = obj.masterOrderId;
          order.masterOrderNo = obj.masterOrderNo
          //物流所需
          if (obj.orderStatus == '31' || obj.orderStatus == '51' || obj.orderStatus == '61') {
            order.createTime = obj.createTime
            order.userName = obj.address.userName
            order.address = obj.address.province + obj.address.city + obj.address.suburb + obj.address.addressDetail
            order.phoneNum = obj.address.userTel
          }

          dataList.push(order);
        }
        this.setData({
          dataList: dataList,
          status: status
        });
      },
      tapTitle: function(event) {
        let status = event.target.id;
        this.loadData(status);
        // debugger
        if (status == '0') { //当点击全部
          this.setData({
            isTotal: false
          })
        }
      },
      // 选择线上订单或者线下订单
      getUnderOrderList: function(e) {
        var that = this
        console.log(e)
        var id = e.target.dataset.id
        if (id == '9') { //如果选择线下订单，请求线下订单接口
          // 将导航线上订单改变成线下订单
          that.data.titleList[0].title = '线下订单'
          console.log(that.data.titleList)
          that.setData({
            titleList: that.data.titleList,
            isUnderLine: false, //隐藏线上订单 显示线下订单
          })
          var page = 1
          var row = 20
          this.setData({
            isTotal: true
          })
          let mohuanUser = app.globalData.mohuanUser
          var memberPho = mohuanUser.memberInfo.phoneNo
          var token = mohuanUser["X-AUTH-TOKEN"]
          //请求线下订单列表
          wx.request({
              url: url + '/c2mwebservice/api/v2/trade/' + memberPho + '/offlineOrderList',
              data: {
                page: page,
                rows: row
              },
              method: 'post',
              header: {
                'Accept': 'application/json',
                'X-AUTH-TOKEN': token,
              },
              success: res => {
                console.log('获取线下订单接口')
                console.log(res)
                var nuderLineItem = res.data.returnData
                that.setData({
                  underList: res.data.returnData
                })
                // 订单图片                              
                for (var i = 0; i < nuderLineItem.length; i++) {
                  var orderImage = ''
                  // debugger
                  var status = nuderLineItem[i].categoryCode
                  switch (nuderLineItem[i].categoryCode) {
                    //女西服 骑马服 中童西服 小童西服
                    case "WXF":
                    case "QMF":
                    case "TXF":
                    case "XXF":
                      orderImage = 'https://source.magicmanufactory.com/image/cottexf.png'
                      // that.setData({
                      //   underItemPic: 'https://source.magicmanufactory.com/image/cottexf.png'
                      // })
                      break;
                      //小童西裤 女西裙 西裤 男短裤 女短裤 女西裤 短裤套装 中童西裤
                    case "XXK":
                    case "WXQ":
                    case "MXK":
                    case "MDK":
                    case "WDK":
                    case "WXK":
                    case "DT":
                    case "TXK":
                      orderImage = 'https://source.magicmanufactory.com/image/cottexk.png'
                      // that.setData({
                      //   underItemPic: 'https://source.magicmanufactory.com/image/cottexk.png'
                      // })
                      break;
                      //马甲 女马甲 中童马甲
                    case "MMJ":
                    case "WMJ":
                    case "TMJ":
                      orderImage = 'https://source.magicmanufactory.com/image/cottemj.png'
                      // that.setData({
                      //   underItemPic: 'https://source.magicmanufactory.com/image/cottemj.png'
                      // })
                      break;
                      //衬衣 女衬衣 中童衬衣
                    case "MCY":
                    case "WCY":
                    case "TCY":
                      orderImage = 'https://source.magicmanufactory.com/image/cottecy.png'
                      // that.setData({
                      //   underItemPic: 'https://source.magicmanufactory.com/image/cottecy.png'
                      // })
                      break;
                      //套装(2pcs) 套装（3pcs） C+B A+C 女套装 中童套装（2pcs） 中童套装（3pcs） 女套装
                    case "T":
                    case "S":
                    case "MMJ_MXK":
                    case "MXF_MMJ":
                    case "W":
                    case "TT":
                    case "TS":
                    case "0":
                      orderImage = 'https://source.magicmanufactory.com/image/cottetz.png'
                      // that.setData({
                      //   underItemPic: 'https://source.magicmanufactory.com/image/cottetz.png'
                      // })
                      break;
                      //马甲
                    case "MJK":
                      orderImage = 'https://source.magicmanufactory.com/image/cottemj.png'
                      that.setData({
                        underItemPic: 'https://source.magicmanufactory.com/image/cottemj.png'
                      })
                      //礼服 大衣 女大衣 男女风衣长短款 中童大衣
                    case "MLF":
                    case "MDY":
                    case "WDY":
                    case "WFS":
                    case "WFL":
                    case "MFS":
                    case "MFL":
                    case "TDY":
                      orderImage = 'https://source.magicmanufactory.com/image/cottedy.png'
                      // that.setData({
                      //   underItemPic: 'https://source.magicmanufactory.com/image/cottedy.png'
                      // })
                    default:
                      orderImage = 'https://source.magicmanufactory.com/image/cotte/default.png'
                      // that.setData({
                      //   underItemPic: 'https://source.magicmanufactory.com/image/cotte/default.png'
                      // })
                  }
                  nuderLineItem[i].imageSrc = orderImage 
                }
              
                that.setData({
                  underList: nuderLineItem
                })
                console.log(that.data.underList)

              }
              })
          }
          // 如果是线上订单
          if (id == '0') { //线上订单
            // 将导航线上订单改变成线下订单
            that.data.titleList[0].title = '线上订单'
            console.log(that.data.titleList)
            that.setData({
              titleList: that.data.titleList,          
            })
            this.setData({
              isTotal: true,
              isUnderLine:true,//隐藏线下订单 展示线上订单
            })
            let status = id;
            this.loadData(status);
          }

        },



        //删除订单
        //我的订单---删除某个订单---后面拼接orderid  method = RequestMethod.DELETE
        //https://www.magicmanufactory.com/c2mwebservice/api/v2/trade/8a248f6f54bc840401550e84bcf91101/myOrders/
        //https://testserver1.magicmanufactory.com/c2mwebservice/api/v2/trade/8a9d6be95c9b5d22015cc88aef720001/myOrders/8a9d6be95cf74e97015cfcbadd35003e
        //getApp().globalData.mohuanUser.memberId
        //event.target.dataset.order.orderId
        presentDeleteButtonAction: function(event) {
            let that = this;
            let order = event.target.dataset.order
            wx.showModal({
              title: '提示',
              content: '是否删除订单',
              confirmText: '是',
              cancalText: '否',
              success: function(res) {
                if (res.confirm) {
                  //https://testserver1.magicmanufactory.com/c2mwebservice/api/v2/trade/8a9d6be95c9b5d22015cc88aef720001/myOrders/8a9d6be95cf74e97015cfcbadd35003e
                  //wo "/c2mwebservice/api/v2/trade/8a248f6f54bc840401550e84bcf91101/myOrders/8a248f6f5c4d5771015cfcd2bc183b2f"
                  //    /c2mwebservice/api/v2/trade/8a248f6f54bc840401550e84bcf91101/myOrders/8a23e8955c4d5a6e015cfc0879ed1382"
                  util.deleteDataRequest(`/c2mwebservice/api/v2/trade/${getApp().globalData.mohuanUser.memberId}/myOrders/${event.target.dataset.order.orderId}`, {
                    "memberId": getApp().globalData.mohuanUser.memberId,
                    "masterOrderId": event.target.dataset.order.orderId
                  }, function(res) {
                    let dataList = that.data.dataList
                    for (let i = 0; i < dataList.length; i++) {
                      if (dataList[i].orderId == order.orderId) {
                        dataList.splice(i, 1);
                        break
                      }
                    }
                    that.setData({
                      dataList: dataList
                    })
                  }, function(res) {})
                }
              }
            })
          },


          //取消订单
          //我的订单---取消某个订单---后面拼接orderid
          presentCancelButtonAction: function(event) {
            let that = this;
            let order = event.target.dataset.order
            wx.showModal({
              title: '提示',
              content: '是否取消订单',
              confirmText: '是',
              cancalText: '否',
              success: function(res) {
                if (res.confirm) {
                  util.postRequest(`/c2mwebservice/api/v2/trade/MEMBER_ID/myOrder/${event.target.dataset.order.orderId}`, null, function(res) {
                    let dataList = that.data.dataList
                    for (let i = 0; i < dataList.length; i++) {
                      if (dataList[i].orderId == order.orderId) {
                        dataList[i].orderStatus = statusDic['01']
                        dataList[i].buttonArr = buttonDic['01']
                        break
                      }
                    }
                    that.setData({
                      dataList: dataList
                    })
                  }, function(res) {
                    console.log(res)
                  })
                }
              }
            })
          },
          //付款
          presentPaymentButtonAction: function(event) {
            let params = {}
            // 套装
            // if (this.data.productInfo.goods.length>1) {
            //     params.totalPrice = this.data.productInfo.suit.suitPrice
            // } else {
            //     params.totalPrice = ''
            // }
            // this.totalPrice = params.totalPrice
            params.totalPrice = event.target.dataset.order.totalPrice;
            params.payInfoItem = [{
              "postage": 0,
              "storeTotalPrice": event.target.dataset.order.totalPrice,
              "payment": {
                "payment": event.target.dataset.order.totalPrice,
              },
              "discount": [],
              "invoice": {
                "address": "",
                "accountBank": "",
                "accountNo": "",
                "invoiceType": "2",
                "taxerName": "个人",
                "companyName": "",
                "phoneNo": "",
                "taxerIdNo": ""
              },
              "price": event.target.dataset.order.totalPrice,
              "separateFlag": "0"
            }]
            params.orderId = event.target.dataset.order.orderId
            params.payment = {
              "payment": event.target.dataset.order.totalPrice
            }
            if (!this.data.addressData.phoneNo) {
              wx.showToast({
                title: '请填写地址',
              })
              return
            }
            params.address = {
              "postCode": this.data.addressData.postal,
              "suburb": this.data.addressData.suburb,
              "city": this.data.addressData.city,
              "userName": this.data.addressData.receiver,
              "addressDetail": this.data.addressData.detail,
              "userTel": this.data.addressData.phoneNo,
              "province": this.data.addressData.province
            }
            wx.showToast({
              title: '加载中',
              icon: 'loading',
              duration: 10000
            })
            let _this = this
            util.postRequest(`/c2mwebservice/api/v2/${this.memberId}/shoppingCarts/trade`, params, function(res) {
              _this._orderPay(params, function(res) {
                wx.hideToast()
              }, function(error) {
                wx.hideToast()
              })
            }, function(error) {
              console.log(error)
              wx.hideToast()
            })

          },
          //调后台取微信支付参数 而后调用微信支付
          _orderPay: function(event, success, failure) {
            var orderId = event.orderId; //订单id
            var totalPrice = event.totalPrice; //价格
            var openid = app.globalData.userInfo.openId; //小程序openId

            //小龙给的参数
            var params = {
              "payMethod": "07",
              "balance": 0,
              "totalPrice": totalPrice,
              "openid": openid, //
              "orderId": [orderId]
            }

            //获取支付参数   调用微信支付
            util.postRequest(`/c2mwebservice/api/v2/tradeOrder/${this.memberId}/orderPay`, params, function(res) {
              var datas = res;
              // debugger
              var packageDate = "prepay_id=" + datas.returnData.widgetCode.prepayid;
              wx.requestPayment({
                'appId': datas.returnData.widgetCode.appId, //小程序ID
                'timeStamp': datas.returnData.widgetCode.timeStamp, //时间戳
                'nonceStr': datas.returnData.widgetCode.nonceStr, //随机字符串，不长于32位
                'package': datas.returnData.widgetCode.package, //数据包
                'signType': 'MD5', //签名方式
                'paySign': datas.returnData.widgetCode.paySign,
                success: function(res) {
                  //如果成功，返回errMsg
                  // errMsg  :  "requestPayment:ok"
                  console.log("=======================>支付成功")
                  wx.navigateTo({
                    url: `../OrderList/OrderList?status=0`,
                    success: function(res) {},
                    fail: function() {},
                    complete: function() {}
                  })
                },
                fail: function(res) {
                  console.log("=======================>支付失败")
                },
                complete: function(res) {
                  console.log("=======================>支付回调")
                }
              })
            }, function(error) {
              wx.showToast({
                title: '加载失败，请稍后再试',
              })
              if (failure) {
                failure(error);
              }
            })
          },
          //查询物流信息
          presentLookWuliuButtonAction: function(event) {
            //console.log(event);
            wx.setStorageSync('wuliuData', event.target.dataset.order)
            wx.navigateTo({
              url: '../wuliuInfo/wuliuInfo',
              success: function(res) {
                // success
              },
              fail: function() {
                // fail
              },
              complete: function() {
                // complete
              }
            })
          },
          //评价
          presentEvaluateButtonAction: function(event) {
            wx.setStorageSync('evaluateData', event.target.dataset.order)
            wx.navigateTo({
              url: '../evaluate/evaluate',
              success: function(res) {
                // success
              },
              fail: function() {
                // fail
              },
              complete: function() {
                // complete
              }
            })
          }

      })